<script setup>
import { ref,reactive } from 'vue'
import { login } from '@/api/manager'
import { useRouter } from "vue-router";
import  {toast} from  "@/composables/util.js"
import { setToken } from '@/composables/auth.js'
import {useTestStore} from '@/store/index.js'

const router = useRouter()
// do not use same name with ref
const form = reactive({
    username: "",
    password: ""
})
const rules = {
    username: [
        {required: true, message: '用户名不能为空', trigger: 'blur'},
        // { min: 3, max: 5, message: '用户名长度为3到5个字符', trigger: 'blur' },
    ],
    password: [
        {required: true, message: '密码不能为空', trigger: 'blur'},
    ],
}

const formRef = ref(null)
const loading = ref(false)
const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return false
        } })
        loading.value = true
        login(form.username, form.password).then(res => {
            if (res.hasOwnProperty('token')){
            toast(form.username+",登录成功","success")
            //登录成功后，保存token
            setToken(res.token)
            //获取用户信息
              const Test = useTestStore()
              Test.setData()
            router.push('/home')}
            else {
              toast(res.msg,"warning")
            }
        }).finally(()=>{
            loading.value = false
        })

}


</script>

<template>
  <el-row class="min-h-screen bg-indigo-500">
    <el-col :lg="16" :md="12" class="flex items-center justify-center flex-col">
      <div>
        <div class="font-bold text-3xl text-light-50 mb-4">Hello</div>
        <div class="text-light-50">站点测试</div>
      </div>
    </el-col>
    <el-col :lg="8" :md="12" class="bg-light-50 flex items-center justify-center flex-col">
      <h2>登录界面</h2>
      <div class="flex items-center justify-center my-5 text-gray-300">
        <span class="h-[1px] w-16 bg-gray-200 "></span>
        <span>账号密码登录</span>
        <span class="h-[1px] w-16 bg-gray-200"></span>
      </div>
      <el-form ref="formRef" :rules="rules" :model="form" class="w-[250px]">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="用户名">
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" placeholder="密码">
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button round color="#626aef" class="w-[250px]" type="primary" @click="onSubmit" :loading="loading">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped>h2 {
  @apply font-bold text-3xl text-gray-800 mb-4;
}</style>